import { Body, Inject, Post } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { OrderOrderEntity } from '../../entity/order';
import { OrderOrderService } from '../../service/order';
import { UserInfoEntity } from '../../../user/entity/info';
import { UserRelationEntity } from '../../../user/entity/user_relation';

/**
 * 订单信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderOrderEntity,
  service: OrderOrderService,
  pageQueryOp: {
    keyWordLikeFields: ['a.orderNo'],
    fieldEq: [
      'a.payStatus',
      'a.isComplete',
      'a.deviceBindUserId',
      'a.deviceBindAgentId',
    ],
    fieldLike: [{ column: 'a.deviceNo', requestParam: 'deviceNo' }],
    where: async (ctx) => {
      const conditions = [];
      const { createTime, endTime } = ctx.request.body || {};
      if (createTime) {
        conditions.push(['a.createTime >= :startTime', { startTime: createTime }]);
      }
      if (endTime) {
        conditions.push(['a.createTime <= :endTime', { endTime }]);
      }
      return conditions;
    },
    join: [
      {
        entity: UserInfoEntity,
        alias: 'b',
        condition: 'a.deviceBindUserId = b.id',
      },
      {
        entity: UserRelationEntity,
        alias: 'c',
        condition: 'a.deviceBindUserId = c.userId',
      },
      {
        entity: UserInfoEntity,
        alias: 'd',
        condition: 'a.deviceBindAgentId = d.id',
      },
    ],
    select: [
      'a.*',
      'b.phone AS deviceBindPhone',
      'b.nickName AS deviceBindNickName',
      'c.level1ParentId',
      'c.level2ParentId',
      'c.level3ParentId',
      'd.nickName AS deviceBindAgentNickName',
    ],
    addOrderBy: {
      'a.createTime': 'DESC',
    },
  },
})
export class AdminOrderOrderController extends BaseController {
  @Inject()
  orderOrderService: OrderOrderService;

  /* 退款 */
  // 手动投币
  @Post('/refund')
  async refund(@Body() params) {
    const _res = await this.orderOrderService.refund(params);

    console.log('_res', _res);

    if (_res?.code === 'BBS11000') {
      /* 报错 */
      return this.fail(_res.msg);
    }

    return this.ok(_res);
  }

  @Post('/sum')
  async sum(@Body() params: any) {
    const total = await this.orderOrderService.sumByFilterAdmin(params);
    return this.ok({ total });
  }

  @Post('/refundSum')
  async refundSum(@Body() params: any) {
    const total = await this.orderOrderService.refundSumByFilterAdmin(params);
    return this.ok({ total });
  }
}
